package com.csw.mybatisSpringboot.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csw.mybatisSpringboot.config.page.PageResult;
import com.csw.mybatisSpringboot.config.page.PageResultUtil;
import com.csw.mybatisSpringboot.dto.UserListDto;
import com.csw.mybatisSpringboot.dto.UserSaveDto;
import com.csw.mybatisSpringboot.entity.User;
import com.csw.mybatisSpringboot.mapper.UserMapper;
import com.csw.mybatisSpringboot.util.NanoIdUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author 1
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Override
    public PageResult<User> selectAllByName(UserListDto dto) {
        Page page = new Page<>(dto.getPageNo(), dto.getPageSize());
        Page<User> userList = baseMapper.selectAllByName(page, dto);

        PageResult<User> pageResult = PageResultUtil.getPageResult(userList);
        return pageResult;
    }

    @Override
    public void addOrUpdate(UserSaveDto dto) {
        User user = BeanUtil.copyProperties(dto, User.class);
        if (StringUtils.isEmpty(user.getId())) {
            user.setId(NanoIdUtil.getNanoId());
            baseMapper.insert(user);
        } else {
            LambdaQueryWrapper w1 = Wrappers.<User>lambdaQuery().eq(User::getId, user.getId());
            baseMapper.update(user, w1);
            //baseMapper.updateById(user);
        }
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void updateTest() {
        User user = baseMapper.selectTestForUpdate();
        user.setUpdateTime(new Date());
        baseMapper.updateById(user);
    }

    @Override
    @Transactional
    public void selectTest() {
        User user = baseMapper.selectTest();
        User user1 = baseMapper.selectTest();
        User user2 = baseMapper.selectTest();
        User user3 = baseMapper.selectTest();
    }

//    @Override
//    public PageResult<User> selectAllByName2(UserListDto dto) {
//        List<User> userList = baseMapper.selectList(Wrappers.<User>lambdaQuery().eq(User::getName, dto.getName()));
//
//        PageResult<User> pageResult = PageResultListUtils.getPageResult(dto.getPageNo(), dto.getPageSize(), userList);
//        return pageResult;
//    }
}
